package com.junxonline.common.util;

import com.junxonline.common.exception.CommonBizException;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class FileUtils {

    public static String saveFile(MultipartFile file, String filePath) {

        // 保存时的文件名
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        filePath += dateFormat.format(calendar.getTime()) + "/";
        String fileName = file.getOriginalFilename();

        try {

            File fileDec = new File(filePath);
            if (!fileDec.exists()) {
                fileDec.mkdirs();
            }

            file.transferTo(new File(filePath + fileName));
            return fileDec + "\\" + fileName;

        }
        catch (Exception e) {
            e.printStackTrace();
            throw CommonBizException.SYSTEM_ERROR;
        }
    }

    public static String readFile(String filePath) {

        File file = new File(filePath);

        FileInputStream fileInputStream = null;
        try {
            if (!file.exists()) {
                throw CommonBizException.SYSTEM_ERROR;
            }

            fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[(int)file.length()];
            fileInputStream.read(buffer);
            fileInputStream.close();
            return Base64.encodeBase64String(buffer);
        }
        catch (Exception e) {
            throw CommonBizException.SYSTEM_ERROR;
        }
        finally {
            if (CommonUtils.isNotEmpty(fileInputStream)) {
                fileInputStream = null;
            }
        }

    }


}
